package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.*;
import cc.rengu.igas.momp.common.dao.impl.*;
import cc.rengu.igas.momp.common.entity.*;
import cc.rengu.igas.momp.common.enums.*;
import cc.rengu.igas.momp.common.util.CommonMessageCheck;
import cc.rengu.igas.momp.common.util.JsonOperation;
import cc.rengu.igas.momp.facade.request.EditMcMerListRequest;
import cc.rengu.igas.momp.facade.response.EditMcMerListResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import cc.rengu.utility.base.StringUtil;
import cc.rengu.utility.dbs.Database;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 营销活动商户信息批量上传功能实现
 *
 * @author liujinan
 * @since 2021/6/29 10:59
 */
public class EditMcMerListService extends RadpService {

    private String globalInstId;
    private String globalMcNo;
    private String globalTimeStamp;
    private String globalOprId;
    private String globalTxnDate;
    private String globalMcType;
    private String traceNo = "";
    private String mcSponsor = "";

    @Override
    protected int bizInit(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {

            EditMcMerListRequest editMcMerListRequest = new EditMcMerListRequest();
            ConvertUtil.convertOutput(editMcMerListRequest);

            EditMcMerListResponse editMcMerListResponse = new EditMcMerListResponse();
            editMcMerListResponse.setHeader(editMcMerListRequest.getHeader());
            BizResponse<EditMcMerListResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(editMcMerListResponse);

            /* 判断查询类型 */
            rglog.debug("TXN_NUM=<{}>", editMcMerListRequest.getHeader().getTxnNum());

            globalInstId = editMcMerListRequest.getHeader().getInstId();
            globalTimeStamp = new SimpleDateFormat(CommonConstant.TIMESTAMP_FORMAT).format(new Date());
            globalOprId = editMcMerListRequest.getQueryId();
            globalTxnDate = editMcMerListRequest.getHeader().getTransDate();
            globalMcNo = editMcMerListRequest.getMcNo();
            traceNo = editMcMerListRequest.getHeader().getTraceNo();
            /** 活动类型 */
            globalMcType = globalMcNo.substring(2, 4);

            String queryType = editMcMerListRequest.getQueryType();
            String queryRole = editMcMerListRequest.getQueryRole();

            rglog.debug("QUERY_TYPE=<{}>", queryType);
            rglog.debug("QUERY_ID=<{}>", globalOprId);
            rglog.debug("QUERY_ROLE=<{}>", queryRole);

            /* 报文检查 */
            CommonMessageCheck.checkBizMessageHeader(queryType, globalOprId, queryRole, rglog);

            // 服务调用
            BizResponse<EditMcMerListResponse> bizResponseNew = editMcMerList(editMcMerListRequest, editMcMerListResponse, xmlTreeUtil);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    /**
     * 减免类营销活动编辑方法
     *
     * @param editMcMerListRequest  减免类营销活动信息编辑接口请求对象
     * @param editMcMerListResponse 减免类营销活动信息编辑接口应答对象
     * @param xmlTreeUtil           内部XML树
     * @return cc.rengu.oltp.service.model.BizResponse<cc.rengu.igas.momp.facade.response.EditMcMerListResponse> 减免类营销活动信息编辑接口应答对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @since 2020/5/21 18:15
     */
    private BizResponse<EditMcMerListResponse> editMcMerList(EditMcMerListRequest editMcMerListRequest, EditMcMerListResponse editMcMerListResponse, XmlTreeUtil xmlTreeUtil) throws Exception {

        BizResponse<EditMcMerListResponse> bizResponse = new BizResponse<>();

        /* 判断查询类型 */
        String queryType = editMcMerListRequest.getQueryType();
        String queryRole = editMcMerListRequest.getQueryRole();
        String mcStatus = "";
        /* 判断用户的角色和权限 */
        if (QueryTypeEnum.BANK_QUERY_TYPE.getQueryTypeCode().equals(queryType)) {

            if (QueryRoleEnum.BANK_BASIC_QUERY_ROLE.getQueryRoleCode().equals(queryRole)) {

                /** 对客活动查询活动信息 */
                McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
                if (McTypeEnum.REDUCTION_FIXED_AMOUNT.getMcTypeCode().equals(globalMcType) || McTypeEnum.REDUCTION_RANDOM_AMOUNT.getMcTypeCode().equals(globalMcType) ||
                        McTypeEnum.REDUCTION_FIXED_RATE.getMcTypeCode().equals(globalMcType) || McTypeEnum.REDUCTION_RANDOM_RATE.getMcTypeCode().equals(globalMcType)) {
                    TMMcMoneyOffInfo tmMcMoneyOffInfo = (TMMcMoneyOffInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, globalMcNo, TableNameEnum.T_M_MC_MO_INFO.getTableNameCode());
                    if (tmMcMoneyOffInfo == null) {
                        throw new BizException(RespCodeEnum.GET_MONEY_OFF_MC_LIST_ERROR.getRespCode(), RespCodeEnum.GET_MONEY_OFF_MC_LIST_ERROR.getRespDesc());
                    }
                    mcSponsor = tmMcMoneyOffInfo.getSponsor();
                    mcStatus = tmMcMoneyOffInfo.getMcStatus();
                    /** 卡券类 */
                } else if (McTypeEnum.COUPON_FREE.getMcTypeCode().equals(globalMcType) || McTypeEnum.COUPON_PAID.getMcTypeCode().equals(globalMcType) || McTypeEnum.COUPON_ALL.getMcTypeCode().equals(globalMcType)) {
                    TMMcCouponInfo tmMcCouponInfo = (TMMcCouponInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, globalMcNo, TableNameEnum.T_M_MC_CP_INFO.getTableNameCode());
                    if (tmMcCouponInfo == null) {
                        throw new BizException(RespCodeEnum.GET_COUPON_MC_LIST_ERROR.getRespCode(), RespCodeEnum.GET_COUPON_MC_LIST_ERROR.getRespDesc());
                    }
                    mcSponsor = tmMcCouponInfo.getSponsor();
                    mcStatus = tmMcCouponInfo.getMcStatus();
                    /** 商户手续费类 */
                } else if (McTypeEnum.MCHNT_FEE_DISCOUNT.getMcTypeCode().equals(globalMcType)) {
                    TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, globalMcNo, TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());
                    if (tmMcMchntFeeDiscountInfo == null) {
                        throw new BizException(RespCodeEnum.GET_MCHNT_FEE_DISCOUNT_MC_LIST_ERROR.getRespCode(), RespCodeEnum.GET_MCHNT_FEE_DISCOUNT_MC_LIST_ERROR.getRespDesc());
                    }
                    mcStatus = tmMcMchntFeeDiscountInfo.getMcStatus();
                    /** 收银员返现类 */
                } else if (McTypeEnum.CASHER_CASHBACK.getMcTypeCode().equals(globalMcType)) {
                    TMMcCashierCashbackInfo tmMcCashierCashbackInfo = (TMMcCashierCashbackInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, globalMcNo, TableNameEnum.T_M_MC_CCB_INFO.getTableNameCode());
                    if (tmMcCashierCashbackInfo == null) {
                        throw new BizException(RespCodeEnum.GET_CASHIER_CASHBACK_MC_LIST_ERROR.getRespCode(), RespCodeEnum.GET_CASHIER_CASHBACK_MC_LIST_ERROR.getRespDesc());
                    }
                    mcStatus = tmMcCashierCashbackInfo.getMcStatus();
                } else {
                    rglog.info("营销活动类型异常");
                    throw new BizException(RespCodeEnum.NOT_SUPPORTED_MC_TYPE_ERROR.getRespCode(), RespCodeEnum.NOT_SUPPORTED_MC_TYPE_ERROR.getRespDesc());
                }

                //仅允许草稿状态的营销活动调用该接口进行批量操作
                if (!McStatusEnum.DRAFT.getMcStatusCode().equals(mcStatus)) {
                    throw new BizException(RespCodeEnum.MC_MCHNT_BATCH_STATUS_CHECK_FAIL.getRespCode(), RespCodeEnum.MC_MCHNT_BATCH_STATUS_CHECK_FAIL.getRespDesc());
                }

                String mchntNo = editMcMerListRequest.getMchntNo();
                String[] mchntNos = mchntNo.split(",");
                if (mchntNos.length > 60000) {
                    rglog.info("营销活动：<{}>商户信息批量上传报文校验失败，长度=<{}>", globalMcNo, mchntNos.length);
                    throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
                }
                List<String> mchntNoList = new ArrayList<>();
                Collections.addAll(mchntNoList, mchntNos);

                //判断营销活动是否已经存在商户信息，如存在则抛出异常
                McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
                List<TMMcMchntInfo> tmMcMchntInfoListing = mcMchntInfoMapper.selectMcMchntInfoListByMcNo(globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT);


                rglog.info("营销活动：<{}>查询营销活动是否存在存量商户列表,如存在则抛出异常", globalMcNo);
                if (tmMcMchntInfoListing != null && tmMcMchntInfoListing.size() > 0) {
                    rglog.info("营销活动：<{}>存量商户列表,size=<{}>", globalMcNo, tmMcMchntInfoListing.size());
                    throw new BizException(RespCodeEnum.MC_MCHNT_BATCH_EXIST_ERROR.getRespCode(), RespCodeEnum.MC_MCHNT_BATCH_EXIST_ERROR.getRespDesc());
                }

                /** 查询对应的商户信息 */
                List<TBMchntBaseInfo> mcMchntInfoList = new ArrayList<>();
                /** 查询营销活动机构列表 */
                List<TMMcOrgInfo> orgInfoList = queryMcOrgInfoList();
                /** 筛选商户列表，保留符合条件的商户数据 */
                checkMchntAndOrgInfo(orgInfoList, mchntNoList, mcMchntInfoList);
                rglog.info("营销活动：<{}>校验商户所属机构与活动机构是否匹配，检查完成,商户列表 size=<{}>", globalMcNo, mcMchntInfoList.size());
                //符合营销活动的商户列表数据为空，阻断交易
                if (mcMchntInfoList.isEmpty()) {
                    throw new BizException(RespCodeEnum.MC_MCHNT_BATCH_CHECK_FAIL.getRespCode(), RespCodeEnum.MC_MCHNT_BATCH_CHECK_FAIL.getRespDesc());
                }
                List<TMMcMchntInfo> mcMchntList = mcMchntInfoList.stream().map(this::convertMcMchntInfo).collect(Collectors.toList());
                //保存商户列表
                /* 开启数据库事务 */
                String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
                String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
                if (null != corporation && !corporation.isEmpty()) {
                    String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
                    dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
                }
                DbsUtil dbsUtil = new DbsUtil(dbPoolName);
                dbsUtil.dbsBeginTransaction();

                rglog.info("营销活动：<{}>批量保存商户列表信息size=<{}>", globalMcNo, mcMchntList.size());
                insertMcMchntInfo(dbsUtil, mcMchntList);
                //保存商户临时表
                List<TMPlatBizTmp> tmpMchntList = mcMchntList.stream().map(this::convertMcMchntInfoToTmp).collect(Collectors.toList());
                rglog.info("营销活动：<{}>临时表保存营销活动商户信息，size=<{}>", globalMcNo, tmpMchntList.size());
                insertMultiMcDetialInfoByBank(dbsUtil, tmpMchntList);

                //提交事务
                dbsUtil.dbsEndTransaction(true);
            } else {
                /* 银行审批岗或银行发布岗 */
                rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", queryRole, queryType);
                throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespDesc());
            }
        } else {
            /* 商户、代理商、收银员或用户 */
            rglog.error("当前<{}>角色的查询用户<{}>无权限查看数据!", queryRole, queryType);
            throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_QUERY_ERROR.getRespDesc());
        }

        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        editMcMerListResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        editMcMerListResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        bizResponse.setResult(editMcMerListResponse);

        return bizResponse;
    }

    private List<TBMchntBaseInfo> selectMcMchntInfoList(List<String> mchntNoList) throws Exception {
        List<TBMchntBaseInfo> mchntInfoList = new ArrayList<TBMchntBaseInfo>();

        MchntInfoMapper mchntInfoMapper = new MchntInfoMapperImpl();
        rglog.info("交易流水号：<{}>, 筛选商户信息开始...", traceNo);
        for (String mchntNo : mchntNoList) {
            //查询商户基本信息
            TBMchntBaseInfo tbMchntBaseInfo = mchntInfoMapper.selectMchntBaseInfoByMchntNo(globalInstId, mchntNo);

            if (null == tbMchntBaseInfo) {
                rglog.error("交易流水号：<{}>, 商户<{}>信息查询异常，！", traceNo, mchntNo);
            } else {
                mchntInfoList.add(tbMchntBaseInfo);
            }
        }
        mchntInfoList = mchntInfoList.stream().distinct().collect(Collectors.toList());

        return mchntInfoList;
    }

    /**
     * 查询营销活动机构信息表
     *
     * @throws Exception 异常信息
     * @author liujinan
     * @since 2021/3/29 16:38
     */
    private List<TMMcOrgInfo> queryMcOrgInfoList() throws Exception {
        McOrgInfoMapper mcOrgInfoMapper = new McOrgInfoMapperImpl();
        return mcOrgInfoMapper.selectMcOrgInfoList(globalInstId, globalMcNo);
    }

    private void checkMchntAndOrgInfo(List<TMMcOrgInfo> mcOrgInfoList, List<String> mchntList, List<TBMchntBaseInfo> mcMchntInfoList) throws Exception {

        rglog.info("营销活动：<{}>校验商户所属机构与活动机构是否匹配，检查开始，商户列表size=<{}>", globalMcNo, mchntList.size());
        //处理查询的机构信息
        List<String> orgIdList = mcOrgInfoList.stream().map(item -> item.getOrgId()).collect(Collectors.toList());
        //对机构进行去重处理
        orgIdList = orgIdList.stream().distinct().collect(Collectors.toList());
        int maxLength = mchntList.size();
        MchntInfoMapper mchntInfoMapper = new MchntInfoMapperImpl();
        //获取当前时间
        String date = DateUtil.getCurrentDate();
        List<String> mchntRealOrgList = new ArrayList<>();

        for (String mchntNo : mchntList) {
            rglog.info("交易流水号：<{}>, 查询商户<{}>信息开始...", traceNo, mchntNo);
            //查询商户基本信息
            TBMchntBaseInfo tbMchntBaseInfo = mchntInfoMapper.selectMchntBaseInfoByMchntNo(globalInstId, mchntNo);
            if (null == tbMchntBaseInfo) {
                rglog.error("交易流水号：<{}>, 商户<{}>信息查询异常！", traceNo, mchntNo);
                throw new BizException(RespCodeEnum.GET_MCHNT_BASE_INFO_ERROR_BY_FORMAL.getRespCode(), RespCodeEnum.GET_MCHNT_BASE_INFO_ERROR_BY_FORMAL.getRespDesc() + ",商户号" + mchntNo);
            }
            mcMchntInfoList.add(tbMchntBaseInfo);
            mchntRealOrgList.add(tbMchntBaseInfo.getSignInstId());
        }
        //对请求上送的商户所属的机构进行去重处理
        mchntRealOrgList = mchntRealOrgList.stream().distinct().collect(Collectors.toList());
        //获取营销活动机构列表
        List<String> mcOrgIdList = mcOrgInfoList.stream().map(item -> item.getOrgId()).collect(Collectors.toList());

        //比较通过接口上送的机构号是否包含通过商户筛选出的机构号
        if (mcOrgIdList.containsAll(mchntRealOrgList)) {
            rglog.info("交易流水号：<{}>, 接口上送的机构信息与商户所属机构信息校验通过！", traceNo);
        } else {
            rglog.error("交易流水号：<{}>, 接口上送的机构信息与商户所属机构信息失败！", traceNo);
            throw new BizException(RespCodeEnum.CHECK_MCHNTREALORG_REQUESTORG_FAIL.getRespCode(), RespCodeEnum.CHECK_MCHNTREALORG_REQUESTORG_FAIL.getRespDesc());
        }

        //如果是手续费活动，需要进行其他校验
        if (McTypeEnum.MCHNT_FEE_DISCOUNT.getMcTypeCode().equals(globalMcType)) {
            for (String mchntNo : mchntList) {
                //判断商户是否存在特殊费率，如果有则不允许进行下一步
                List<TBMchntFeeInfo> tbMchntFeeInfoList = mchntInfoMapper.selectMchntFeeInfoListByMchntNo(globalInstId, mchntNo);
                if (null != tbMchntFeeInfoList && tbMchntFeeInfoList.size() > 0) {
                    tbMchntFeeInfoList = tbMchntFeeInfoList.stream().filter(item -> item.getFeeInputMode().equals(CommonConstant.ZERO_COMMON_CONSTANT)).collect(Collectors.toList());
                    if (tbMchntFeeInfoList.size() > 0) {
                        rglog.error("交易流水号：<{}>, 商户<{}>费率信息表存在特殊费率！", traceNo, mchntNo);
                        throw new BizException(RespCodeEnum.EXISTENCE_SPECIAL_FEE.getRespCode(), RespCodeEnum.EXISTENCE_SPECIAL_FEE.getRespDesc());
                    }
                }
                //查询手续费达标统计表是否有该商户现交易日期达标的数据
                TMStatMfdCriteriaMapper tmStatMfdCriteriaMapper = new TMStatMfdCriteriaMapperImpl();
                TMStatMfdCriteria tmStatMfdCriteria = tmStatMfdCriteriaMapper.selectTMStatMfdCriteriaByUsingMchntNoAndDateRange(globalInstId, mchntNo, date);
                if (null != tmStatMfdCriteria) {
                    /* 营销活动信息正式表查询 */
                    McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
                    TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, tmStatMfdCriteria.getMcNo(), TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());
                    //如果达标统计表有当前交易日期商户达标的数据，则直接拒绝新增,原活动状态为自然结束，强制结束，已结束的数据作废
                    if (null != tmMcMchntFeeDiscountInfo && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.FORCE_ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ALL_ENDED.getMcStatusCode())) {
                        rglog.error("交易流水号：<{}>, 商户<{}>已参加其他手续费活动<{}>！", traceNo, mchntNo, tmMcMchntFeeDiscountInfo.getMcNo());
                        throw new BizException(RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespCode(), RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespDesc());
                    }
                }
            }

            //根据活动编号查询活动主表开始日期
            McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, globalMcNo, TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());
            if (tmMcMchntFeeDiscountInfo != null && CommonConstant.STOCK_MCHNT_FLAG_ONE.equals(tmMcMchntFeeDiscountInfo.getStockMchntFlag())) {
                //判断未上送商户号商圈号时，机构下的非特殊费率商户达标统计表是否存该交易日期内的数据
                String mcStartDate = tmMcMchntFeeDiscountInfo.getMcStartDate();
                checkMchntNoAndAreaNo(mcStartDate, mcMchntInfoList);
            }

        }
        rglog.info("营销活动：<{}>校验商户所属机构与活动机构是否匹配，检查完成,商户列表size=<{}>", globalMcNo, mchntList.size());
    }

    /**
     * 判断未上送商户号商圈号时，机构下的非特殊费率商户达标统计表是否存该交易日期内的数据
     *
     * @param mcStartDate         活动开始日期
     * @param mcMchntInfoBeanList 商户列表
     * @throws Exception
     */
    private void checkMchntNoAndAreaNo(String mcStartDate, List<TBMchntBaseInfo> mcMchntInfoBeanList) throws Exception {
        //法人机构号
        McInfoListMapper mcInfoListMapper = new McInfoListMapperImpl();
        //查询当前日期内营销活动
        List<TMMcMchntFeeDiscountInfo> tmMcMchntFeeDiscountInfoList = mcInfoListMapper.selectMchntFeeDiscountMcListInfoForTime(globalInstId, mcStartDate, "", "");
        //如果活动不存在，直接返回
        if (null == tmMcMchntFeeDiscountInfoList || tmMcMchntFeeDiscountInfoList.size() == 0) {
            return;
        }
        //循环取商户信息表存在该商户的活动
        int maxLength = mcMchntInfoBeanList.size();
        for (int i = 0; i < maxLength; i++) {
            TBMchntBaseInfo mcMchntInfoBean = mcMchntInfoBeanList.get(i);
            String mchntNo = mcMchntInfoBean.getMchntNo();
            //查询营销商户表数据
            McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
            List<TMMcMchntInfo> tmMcMchntInfoList = mcMchntInfoMapper.selectMfdMchntInfoListByinstIdMchntNo(globalInstId, mchntNo);
            if (null == tmMcMchntInfoList || tmMcMchntInfoList.size() == 0) {
                continue;
            }
            rglog.info("查询营销活动商户信息表数据该商户<{}>数据,共<{}>条", mchntNo, tmMcMchntInfoList.size());
            tmMcMchntInfoList = tmMcMchntInfoList.stream().filter(item -> item.getMcNo().contains("MC20")).collect(Collectors.toList());
            rglog.info("属于银行对商户手续费营销活动的条数<{}>", tmMcMchntInfoList.size());
            if (tmMcMchntInfoList.size() == 0) {
                continue;
            }
            tmMcMchntInfoList = tmMcMchntInfoList.stream().filter(item -> !item.getNewMchntFlag().equals(CommonConstant.MCHNT_REFUSE_FLAG) && !item.getExitFlag().equals(CommonConstant.MC_EXIT_FLAG)).collect(Collectors.toList());
            rglog.info("符合银行对商户手续费营销活动的条数<{}>", tmMcMchntInfoList.size());
            if (tmMcMchntInfoList.size() == 0) {
                continue;
            }
            //上送商户是否参加了当前日期内其他进行中的手续费营销活动(new_mchnt_flag为1 exit_flag为1) (new_mchnt_flag为0 exit_flag为0)(new_mchnt_flag为0 exit_flag为1)
            List<TMMcMchntInfo> jxzMchntList = tmMcMchntInfoList.stream().filter(item -> (item.getNewMchntFlag().equals(CommonConstant.MCHNT_OLD_FLAG) && item.getExitFlag().equals(CommonConstant.MC_NOT_EXIT_FLAG)) || (item.getNewMchntFlag().equals(CommonConstant.MCHNT_NEW_FLAG) && item.getExitFlag().equals(CommonConstant.MC_EXIT_FLAG))
                    || (item.getNewMchntFlag().equals(CommonConstant.MCHNT_OLD_FLAG) && item.getExitFlag().equals(CommonConstant.MC_EXIT_FLAG))).collect(Collectors.toList());
            rglog.info("营销活动商户信息表状态为(new_mchnt_flag为1 exit_flag为1)或(new_mchnt_flag为0 exit_flag为0)或(new_mchnt_flag为0 exit_flag为1)的条数<{}>", jxzMchntList.size());
            if (jxzMchntList.size() > 0) {
                for (TMMcMchntInfo tmMcMchntInfo : jxzMchntList) {
                    /* 营销活动信息正式表查询 */
                    McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
                    TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, tmMcMchntInfo.getMcNo(), TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());
                    //如果活动状态不是自然结束，强制结束，草稿；审批状态不是新增拒绝，审批拒绝，发布拒绝的状态，直接抛异常
                    if (null != tmMcMchntFeeDiscountInfo && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.FORCE_ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ALL_ENDED.getMcStatusCode())
                            && !tmMcMchntFeeDiscountInfo.getAuditStatus().equals(AuditStatusEnum.NEW_AUDIT_REJECT.getAuditStatusCode()) && !tmMcMchntFeeDiscountInfo.getAuditStatus().equals(AuditStatusEnum.MODIFY_AUDIT_REJECT.getAuditStatusCode()) && !tmMcMchntFeeDiscountInfo.getAuditStatus().equals(AuditStatusEnum.PUBLISH_AUDIT_REJECT.getAuditStatusCode())
                            && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.DRAFT.getMcStatusCode())) {
                        rglog.error("商户<{}>已参加其他进行中手续费活动<{}>,移除该商户！", tmMcMchntInfo.getMchntNo(), tmMcMchntFeeDiscountInfo.getMcNo());
                        mcMchntInfoBeanList.remove(mcMchntInfoBean);
                        maxLength--;
                        i--;
                        continue;
                    }
                }
            }
            //上送商户是否有从a活动到b活动的转移(new_mchnt_flag为2 exit_flag为2) (new_mchnt_flag为1 exit_flag为2)
            List<TMMcMchntInfo> zyMchntList = tmMcMchntInfoList.stream().filter(item -> (item.getNewMchntFlag().equals(CommonConstant.MCHNT_REFUSE_FLAG) && item.getExitFlag().equals(CommonConstant.MC_TRANSFER_FLAG)) || (item.getNewMchntFlag().equals(CommonConstant.MCHNT_NEW_FLAG) && item.getExitFlag().equals(CommonConstant.MC_TRANSFER_FLAG))).collect(Collectors.toList());
            rglog.info("营销活动商户信息表状态为(new_mchnt_flag为2 exit_flag为2)或(new_mchnt_flag为1 exit_flag为2)的条数<{}>", zyMchntList.size());
            if (zyMchntList.size() > 0) {
                for (TMMcMchntInfo tmMcMchntInfo : zyMchntList) {
                    /* 营销活动信息正式表查询 */
                    McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
                    TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, tmMcMchntInfo.getMcNo(), TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());
                    if (null != tmMcMchntFeeDiscountInfo && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.FORCE_ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ALL_ENDED.getMcStatusCode())) {
                        rglog.error("商户<{}>正在进行活动转移,移除该商户！", tmMcMchntInfo.getMchntNo(), tmMcMchntFeeDiscountInfo.getMcNo());
                        mcMchntInfoBeanList.remove(mcMchntInfoBean);
                        maxLength--;
                        i--;
                        continue;
                    }
                }
            }
        }

    }

    /**
     * 营销活动商户信息数据库实体类和接口实体类数据转换
     *
     * @param mchntBaseInfo 商户信息对象
     * @return cc.rengu.igas.momp.common.entity.TMMcMchntInfo 营销活动商户信息表
     * @author liujinan
     * @since 2021/4/1 14:10
     */
    private TMMcMchntInfo convertMcMchntInfo(TBMchntBaseInfo mchntBaseInfo) {
        TMMcMchntInfo mcMchntInfo = new TMMcMchntInfo();
        try {
            /* 法人机构号 */
            mcMchntInfo.setInstId(globalInstId);
            /* 营销活动编号 */
            mcMchntInfo.setMcNo(globalMcNo);

            //商户信息
            /* 商户范围类型0-商户 */
            mcMchntInfo.setMchntType(CommonConstant.ZERO_COMMON_CONSTANT);
            /* 商户范围号 */
            mcMchntInfo.setMchntNo(mchntBaseInfo.getMchntNo());
            /* 商户范围名称 */
            mcMchntInfo.setMchntName(mchntBaseInfo.getMchntName());

            //非对客营销活动
            if (StringUtil.isNullorEmpty(mcSponsor)) {
                /* 新增商户标志 */
                mcMchntInfo.setNewMchntFlag(CommonConstant.MCHNT_OLD_FLAG);
                /* 退出标志 */
                mcMchntInfo.setExitFlag(CommonConstant.MC_NOT_EXIT_FLAG);

            } else {
                if (CommonConstant.SPONSOR_MIXED.equals(mcSponsor)) {
                    /* 联合营销活动初始数据 */

                    /* 新增商户标志 */
                    mcMchntInfo.setNewMchntFlag(CommonConstant.MCHNT_OLD_FLAG);
                    /* 退出标志 */
                    mcMchntInfo.setExitFlag(CommonConstant.MC_EXIT_FLAG);
                } else {
                    /* 银行全资或商户全资初始数据 */

                    /* 新增商户标志 */
                    mcMchntInfo.setNewMchntFlag(CommonConstant.MCHNT_OLD_FLAG);
                    /* 退出标志 */
                    mcMchntInfo.setExitFlag(CommonConstant.MC_NOT_EXIT_FLAG);
                }
            }

            /* 达标日期 */
            mcMchntInfo.setQualifiedDate(globalTxnDate);
            /* 创建人 */
            mcMchntInfo.setOprId(globalOprId); //取活动创建人
            /* 创建时间 */
            mcMchntInfo.setCreateTime(globalTimeStamp);//取活动创建时间

        } catch (Exception e) {
            rglog.error("转换营销活动商户信息异常,异常信息:<{}>", StringUtil.ExceptionToString(e));
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        return mcMchntInfo;
    }

    /**
     * 营销活动商户信息表数据转换
     * 正式表数据转换为临时表数据
     *
     * @param tmMcMchntInfo 营销活动商户信息表
     * @return cc.rengu.igas.momp.common.entity.TMPlatBizTmp 业务数据临时表
     * @author Jinan Liu
     * @since 2020/5/28 22:26
     */
    private TMPlatBizTmp convertMcMchntInfoToTmp(TMMcMchntInfo tmMcMchntInfo) {

        TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();

        try {
            /* 法人机构标识 */
            tmPlatBizTmp.setInstId(tmMcMchntInfo.getInstId());
            /* 营销活动编号 */
            tmPlatBizTmp.setMcNo(tmMcMchntInfo.getMcNo());
            /* 商户编号 */
            tmPlatBizTmp.setMchntNo(tmMcMchntInfo.getMchntNo());
            /* 操作菜单 */
            tmPlatBizTmp.setOprMenuId(CommonConstant.DEFAULT_MENU_ID);
            /* 操作菜单名 */
            tmPlatBizTmp.setOprMenuName(CommonConstant.DEFAULT_MENU_NAME);
            /* 操作表中文名 */
            tmPlatBizTmp.setOprTableCname(TableNameEnum.T_M_MC_MCHNT_INFO.getTableNameDesc());
            /* 操作表英文名 */
            tmPlatBizTmp.setOprTableEname(TableNameEnum.T_M_MC_MCHNT_INFO.getTableNameCode());
            /* 操作 */
            tmPlatBizTmp.setBizOpr(BizOprEnum.INSERT.getBizOprCode());
            /* 新增商户标志 */
            tmMcMchntInfo.setNewMchntFlag(CommonConstant.MCHNT_OLD_FLAG);
            /* 退出标志 */
            tmMcMchntInfo.setExitFlag(CommonConstant.MC_NOT_EXIT_FLAG);
            /* 达标日期 */
            tmMcMchntInfo.setQualifiedDate(globalTxnDate);
            /* 数据域1 - 拼接JSON字符串 */
            tmPlatBizTmp.setBizData1(JsonOperation.packMcMchntInfoTmpBizData1(tmMcMchntInfo, rglog));
            /* 状态 */
            tmPlatBizTmp.setBizStatus(BizStatusEnum.TMP_STATUS.getBizStatusCode());
            /* 营销活动状态 */
            tmPlatBizTmp.setMcStatus(McStatusEnum.DRAFT.getMcStatusCode());
            /* 审批状态 */
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.WAIT_FOR_SUBMIT.getAuditStatusCode());
            /* 创建人 */
            tmPlatBizTmp.setOprId(globalOprId);
            /* 创建时间 */
            tmPlatBizTmp.setCreateTime(globalTimeStamp);
            /* 使用remark1字段存储商户范围 */
            tmPlatBizTmp.setRemark1(tmMcMchntInfo.getMchntType());

            return tmPlatBizTmp;

        } catch (Exception e) {
            rglog.error("公共业务数据不可为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
    }


    /**
     * 插入营销活动商户信息
     *
     * @param mcMchntInfoList 营销活动商户信息表
     * @throws Exception 异常信息
     * @author liujinan
     * @since 2021/4/1 17:05
     */
    private void insertMcMchntInfo(DbsUtil dbsUtil, List<TMMcMchntInfo> mcMchntInfoList) throws Exception {
        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        int returnCode = mcMchntInfoMapper.insertMcMchntInfoListByBank(mcMchntInfoList);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("新增营销活动商户信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    /**
     * 将营销活动机构信息插入临时表中
     *
     * @param dbsUtil          数据库操作工具类
     * @param tmPlatBizTmpList 业务数据临时表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @since 2020/5/28 22:17
     */
    private void insertMultiMcDetialInfoByBank(DbsUtil dbsUtil, List<TMPlatBizTmp> tmPlatBizTmpList) throws Exception {
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        int returnCode = platBizTmpMapper.insertMultiMcDetialInfoByBank(tmPlatBizTmpList);
        if (Database.DBS_SUCCESS != returnCode) {
            /* 异常结束数据库事务 */
            rglog.error("新增营销活动商户信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

}
